// pages/store/addAddress/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '胡贵烽',
    region: "北京市,北京市,东城区",
    site: '北京民族大学',
    postcode: '100010',
    phone: '13562938889'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  // 选择城市
  bindPickerChange(e) {
    const postcode = e.detail.postcode
    const region = e.detail.value
    this.setData({
      region,
      postcode
    })
  },
  // 保存
  saveAddress() {
    const {
      name,
      region,
      site,
      postcide,
      phone
    } = this.data
    if (!name) {
      wx.showToast({
        title: '请填写收件人',
        icon: 'none'
      })
      return
    }
    if (region.length == 0) {
      wx.showToast({
        title: '请选择地区',
        icon: 'none'
      })
      return
    }
    if (!site) {
      wx.showToast({
        title: '请填写详细地区',
        icon: 'none'
      })
      return
    }
    if (site.length < 5) {
      wx.showToast({
        title: '详情不少于5个字',
        icon: 'none'
      })
      return
    }
    if (!phone) {
      wx.showToast({
        title: '请填写电话号码',
        icon: 'none'
      })
      return
    }
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      wx.showToast({
        title: '手机号码错误',
        icon: 'none'
      })
      return
    }
    this.setData({
      id:Date.now()
    })
    const cardAddress = wx.getStorageSync('cardAddress') || []
    console.log(cardAddress.length)
    if (cardAddress.length >= 3) {
      cardAddress[0] = this.data
    } else {
      cardAddress.unshift(this.data)
    }
   const newCart = cardAddress.map((item, index) => {
      if (index == 0) {
        item.select = true
      } else {
        item.select = false
      }
      return item
    })

    wx.setStorageSync('cardAddress', newCart)
    wx.navigateBack()
  }
})